import React from 'react';
import {connect} from 'dva';
import { Toast, List, Switch, InputItem, DatePicker, Picker, Checkbox, Button } from 'antd-mobile';
import styles from './index.less';
import ScModal from '@/components/searchCity';
import UserServices from '@/services/user';
import { getMastId, requestSuccess } from '@/utils/tools';
const CheckboxItem = Checkbox.CheckboxItem;

/**
 * 真实出差详情 **
 */
class cActualTravelDetails extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      datepickerActiveKey: '',
      datepickerVisible: false
    }
  }

  handleListLabel = (list) => {
    return global._.map(list, item => {
      return {
        label: item,
        value: item
      }
    });
  }


  handleSiteCheckboxChange = (value, key) => {
    value += '';
    const values = this.props.detail.mast[key];
    let arr = [];
    if(values.indexOf(value) !== -1){
      arr = global._.filter(values, (item) => {
        return item !== value;
      })
    }else{
      arr = values.concat([value]);
    }
    arr = global._.uniq(arr);
    console.log(arr);
    this.onChange(arr, key);
  }

  handleShowDatePicker = (activeKey) => {
    if(!this.props.edit)return;
    this.setState({
      datepickerActiveKey: activeKey,
      datepickerVisible: true
    })
  }

  handleSaveDatepickerValue = (date) => {
    if(this.state.datepickerActiveKey){
      this.onChange(global.moment(date).format('YYYY-MM-DD').valueOf(), this.state.datepickerActiveKey);
      this.setState({
        datepickerVisible: false
      })
    }
  }

  handleShowCities = (key) => {
    ScModal.open({
      success: (data)=>{
        const newArr = this.props.detail.mast[key].concat([`${data.cityNameEn}_${data.cityNameCn}`]);
        this.onChange(newArr, key);
      }
    })
  }

  handleDelDetailDestinationItem = (e, item) => {
    e.stopPropagation();
    const newArr = global._.filter(this.props.detail.mast.citiesChange, children=>{
      return children !== item;
    });
    this.onChange(newArr, 'citiesChange');
  }

  handleEditDetailDestinationItem = (index, item) => {
    ScModal.open({
      state: 'edit',
      enKeyword: item.split('_')[0],
      success: (data)=>{
        let newArr = this.props.detail.mast.citiesChange;
        newArr[index] = `${data.cityNameEn}_${data.cityNameCn}`;
        this.onChange(newArr, "citiesChange");
      }
    })
  }

  handleSaveActualInfo = () => {
    const id = getMastId();
    const mast = this.props.detail.mast;

    // copyActualDetail
    const needCompare = ['citiesChange', 'dptrDayChange', 'expDptrDayStatusChange', 'rtnDayChange', 'expRtnDayStatusChange', 'typeChange', 'purposeChange'];
    let targetLabels = global._.filter(needCompare, item => {
      const orginItem = item.replace('Change', '');
      let orgin = this.props.detail.copyActualDetail[orginItem];
      let current = mast[item];
      if(item == 'dptrDayChange' || item == 'rtnDayChange'){
        current = global.moment(mast[item]).valueOf() || '';
      }
      if(current && (current + '').length > 0 && !global._.isEqual(orgin, current) && !mast[item.replace('Change', 'Reason')]){
        return true;
      }
    });
    if(targetLabels && targetLabels.length > 0){
      Toast.fail(`You mast input reason when ${targetLabels[0]} changed`);
      return;
    }

    const data = {
      ...id,
      trsMast: {
        citiesChange: mast.citiesChange,
        citiesReason: mast.citiesReason || '',
        dptrDayChange: mast.dptrDayChange && global.moment(mast.dptrDayChange).format('YYYY-MM-DD') || '',
        dptrDayReason: mast.dptrDayReason || '',
        expDptrDayStatusChange: mast.expDptrDayStatusChange,
        expDptrDayStatusReason: mast.expDptrDayStatusReason || '',
        rtnDayChange: mast.rtnDayChange && global.moment(mast.rtnDayChange).format('YYYY-MM-DD') || '',
        rtnDayReason: mast.rtnDayReason || '',
        expRtnDayStatusChange: mast.expRtnDayStatusChange,
        expRtnDayStatusReason: mast.expRtnDayStatusReason || '',
        requestorRemarks: mast.requestorRemarks,
        needAdvance: mast.needAdvance?'YES':'NO',
        needReimbursement: mast.needReimbursement?'YES':'NO',
        subCompanysChange: mast.subCompanysChange,
        typeChange: mast.typeChange,
        typeReason: mast.typeReason || '',
        subCompanysReason: mast.typeReason || '', //与type合并
        purposeChange: mast.purposeChange,
        purposeReason: mast.purposeReason || ''
      }
    }
    UserServices.saveViewWorkflowEntryOfActualDetails(data).then(res => {
      console.log(res);
      if(requestSuccess(res)){
        //更新copyActualDetail
        // this.props.dispatch({type: 'detail/getData'}).then(() => {
          Toast.success('Save Success');
        // });
      }
    }).then((e) => {
      if(e){
        const message = e.message || 'Error';
        Toast.fail(message);
      }
    })
  }

  onChange = (value, key) => {
    this.props.dispatch({type: 'detail/changeMast', payload: {
      [key]: value
    }});
  }

  render(){
    // citiesChange
    const data = [
      { value: 0, label: 'Ph.D.' },
      { value: 1, label: 'Bachelor' },
      { value: 2, label: 'College diploma' },
    ];
    return (
      <div className={styles.baseList}>
        <DatePicker
          visible={this.state.datepickerVisible}
          mode='date'
          onOk={this.handleSaveDatepickerValue}
          onDismiss={() => this.setState({ datepickerVisible: false })}
        />
        {
          this.props.edit
          ?
          <div className={`${styles.item} ${styles.blockItem}`}>
            <div className={styles.des}>*Actual Destinations</div>
            <div className={styles.value}>
              {
                this.props.detail.mast.citiesChange && this.props.detail.mast.citiesChange.map((item, index) => {
                  return (
                    <div style={{width: '100%'}} key={item} onClick={()=>this.handleEditDetailDestinationItem(index, item)}>
                      {
                        index === 0
                        ?
                        <div>From(City)</div>
                        :
                        null
                      }
                      {
                        index === 1
                        ?
                        <div>To(City)</div>
                        :
                        null
                      }
                      <div className={styles.destinationItem} key={item}>
                        <div className={styles.destination}>{item}</div>
                        <div className={styles.action}>
                          <Button style={{width: '80px', margin: '5px'}} onClick={(e)=>this.handleDelDetailDestinationItem(e, item)}>Delete</Button>
                        </div>
                      </div>
                    </div>

                  )
                })
              }
              {/*
                this.props.detail.mast.citiesChange && this.props.detail.mast.citiesChange.map(item => {
                  return (
                    <div className={styles.destinationItem} key={item}>
                      <div className={styles.destination}>{item}</div>
                      {
                        this.props.edit
                        ?
                        <div className={styles.action}>
                          <Button style={{width: '80px', margin: '5px'}} onClick={(e)=>this.handleDelDetailDestinationItem(e, item)}>Delete</Button>
                        </div>
                        :
                        null
                      }
                    </div>

                  )
                })
              */}
              {
                !this.props.edit
                ?
                null
                :
                <Button style={{width: '150px', margin: '5px'}} onClick={() => this.handleShowCities('citiesChange')}>Add</Button>
              }
            </div>
          </div>
          :
          <div className={styles.item}>
            <div className={styles.des}>*Actual Destinations</div>
            <div className={styles.value}>
              <div className={styles.cities}>
                <div className={styles.textDes}>Departure City：</div>
                {
                  this.props.detail.mast && this.props.detail.mast.citiesChange && this.props.detail.mast.citiesChange[0]
                }
                <div className={styles.textDes}>Destination City：</div>
                {
                  this.props.detail.mast && this.props.detail.mast.citiesChange ?
                  this.props.detail.mast.citiesChange.filter((item, index) => index > 0).join('；')
                  :
                  null
                }
              </div>
            </div>
          </div>
        }
        <div className={styles.item}>
          <div className={styles.des}>Reason For Change Destinations</div>
          <div className={styles.value}>
            <InputItem
              clear
              disabled={!this.props.edit}
              placeholder="click input"
              value={this.props.detail.mast.citiesReason}
              onChange={(value) => this.onChange(value, 'citiesReason')}
            ></InputItem>
          </div>
        </div>
        <div className={styles.item}>
          <div className={styles.des}>Actual Departure Date</div>
          <div className={styles.value} onClick={() => this.handleShowDatePicker('dptrDayChange')}>
              {this.props.detail.mast.dptrDayChange && global.moment(this.props.detail.mast.dptrDayChange).format('YYYY-MM-DD') || 'Select'}
          </div>
        </div>
        <div className={styles.item}>
          <div className={styles.des}>Reason For Change Departure Date</div>
          <div className={styles.value}>
            <InputItem
              clear
              disabled={!this.props.edit}
              placeholder="click input"
              value={this.props.detail.mast.dptrDayReason}
              onChange={(value) => this.onChange(value, 'dptrDayReason')}
            ></InputItem>
          </div>
        </div>
        <Picker disabled={!this.props.edit} data={this.handleListLabel(this.props.detail.expDptrDayStatusList)} cols={1} onChange={(values) => this.onChange(values[0], 'expDptrDayStatusChange')}>
          <div className={styles.item}>
            <div className={styles.des}>Actual Departure Time Zone</div>
            <div className={styles.value}>
                {this.props.detail.mast.expDptrDayStatusChange || 'Select'}
            </div>
          </div>
        </Picker>
        <div className={styles.item}>
          <div className={styles.des}>Reason For Change Departure Time</div>
          <div className={styles.value}>
            <InputItem
              clear
              disabled={!this.props.edit}
              placeholder="click input"
              value={this.props.detail.mast.expDptrDayStatusReason}
              onChange={(value) => this.onChange(value, 'expDptrDayStatusReason')}
            ></InputItem>
          </div>
        </div>
        {
          this.props.detail.mast.isOneWay == 'YES'
          ?
          null
          :
          <div className={styles.item}>
            <div className={styles.des}>Actual Return Date</div>
            <div className={styles.value}  onClick={() => this.handleShowDatePicker('rtnDayChange')}>
              {this.props.detail.mast.rtnDayChange && global.moment(this.props.detail.mast.rtnDayChange).format('YYYY-MM-DD') || 'Select'}
            </div>
          </div>
        }
        {
          this.props.detail.mast.isOneWay == 'YES'
          ?
          null
          :
          <div className={styles.item}>
            <div className={styles.des}>Reason For Change Return Date</div>
            <div className={styles.value}>
              <InputItem
                clear
                disabled={!this.props.edit}
                placeholder="click input"
                value={this.props.detail.mast.rtnDayReason}
                onChange={(value) => this.onChange(value, 'rtnDayReason')}
              ></InputItem>
            </div>
          </div>
        }
        {
          this.props.detail.mast.isOneWay == 'YES'
          ?
          null
          :
          <Picker disabled={!this.props.edit} data={this.handleListLabel(this.props.detail.expRtnDayStatusList)} cols={1} onChange={(values) => this.onChange(values[0], 'expRtnDayStatusChange')}>
            <div className={styles.item}>
              <div className={styles.des}>Actual Return Time Zone</div>
              <div className={styles.value}>
                {this.props.detail.mast.expRtnDayStatusChange || 'Select'}
              </div>
            </div>
          </Picker>
        }
        {
          this.props.detail.mast.isOneWay == 'YES'
          ?
          null
          :
          <div className={styles.item}>
            <div className={styles.des}>Reason For Change Return Time</div>
            <div className={styles.value}>
              <InputItem
                clear
                disabled={!this.props.edit}
                placeholder="click input"
                value={this.props.detail.mast.expRtnDayStatusReason}
                onChange={(value) => this.onChange(value, 'expRtnDayStatusReason')}
              ></InputItem>
            </div>
          </div>
        }
        <Picker disabled={!this.props.edit} data={this.handleListLabel(this.props.detail.allTravelTypes)} cols={1} onChange={(values) => this.onChange(values[0], 'typeChange')}>
          <div className={styles.item}>
            <div className={styles.des}>Actual Type</div>
            <div className={styles.value}>{this.props.detail.mast.typeChange || 'Select'}</div>
          </div>
        </Picker>
        {
          this.props.detail.mast.typeChange == 'Site Office Visit'
          ?
            <div className={`${styles.item} ${styles.blockItem}`}>
              <div className={styles.des}>Actual Visit Site</div>
              <div className={styles.value}>
                <div className={styles.checkList}>
                  <List>
                  {this.props.detail.mobileAllSiteOffices.map(i => (
                    <CheckboxItem key={i.id} disabled={!this.props.edit} checked={this.props.detail.mast.subCompanysChange.find(selectedItem => selectedItem == i.id)?true:false} onChange={() => this.handleSiteCheckboxChange(i.id, 'subCompanysChange')}>
                      {i.siteLocation}
                    </CheckboxItem>
                  ))}
                  </List>
                </div>
              </div>
            </div>
          :
          null
        }
        <div className={styles.item}>
          <div className={styles.des}>Reason For Change Type</div>
          <div className={styles.value}>
            <InputItem
              clear
              disabled={!this.props.edit}
              placeholder="click input"
              value={this.props.detail.mast.typeReason}
              onChange={(value) => this.onChange(value, 'typeReason')}
            ></InputItem>
          </div>
        </div>
        <div className={styles.item}>
          <div className={styles.des}>Actual Purpose of trip</div>
          <div className={styles.value}>
            <InputItem
              clear
              disabled={!this.props.edit}
              placeholder="click input"
              value={this.props.detail.mast.purposeChange}
              onChange={(value) => this.onChange(value, 'purposeChange')}
            ></InputItem>
          </div>
        </div>
        <div className={styles.item}>
          <div className={styles.des}>Reason For Change Purpose</div>
          <div className={styles.value}>
            <InputItem
              clear
              disabled={!this.props.edit}
              placeholder="click input"
              value={this.props.detail.mast.purposeReason}
              onChange={(value) => this.onChange(value, 'purposeReason')}
            ></InputItem>
          </div>
        </div>
        {
          this.props.edit
          ?
          <div className={styles.submitInfoBtn}>
            <Button onClick={()=>this.handleSaveActualInfo()}>Save Info</Button>
          </div>
          :
          null
        }
      </div>
    )
  }
}


function mapStateToProps(state) {
  return {
    ...state.detail
  }
}
export default connect(mapStateToProps)(cActualTravelDetails);
